package com.kasax.httpsupport;

import android.text.TextUtils;

import com.kasax.httpsupport.utils.Util;

import java.util.HashMap;
import java.util.Map;

public class Request {
    HttpMethod httpMethod;

    String url;

    Map<String, String> headers;
    RequestBody body;

    public Request(Builder builder) {
        this.httpMethod = builder.httpMethod;
        this.url = builder.url;
        this.headers = builder.headers;
        this.body = builder.body;
    }

    public enum HttpMethod {
        GET("GET"), POST("POST");


        private final String methodName;

        HttpMethod(String methodName) {
            this.methodName = methodName;
        }

        public String getMethodName() {
            return methodName;
        }

        public static boolean checkNeedBody(HttpMethod method) {
            return POST.equals(method);
        }

        public static boolean checkNoBody(HttpMethod method) {
            return GET.equals(method);
        }
    }

    public static class Builder {
        HttpMethod httpMethod;

        String url;

        Map<String, String> headers;

        RequestBody body;

        public Builder() {
            headers = new HashMap<>();
        }

        public Builder body(RequestBody body) {
            this.body = body;
            return this;
        }

        public Builder url(String url) {
            this.url = url;
            return this;
        }

        public Builder get() {
            this.httpMethod = HttpMethod.GET;
            return this;
        }

        public Builder method(HttpMethod method, RequestBody body) {
            Util.checkMethod(method, body);
            this.httpMethod = method;
            this.body = body;
            return this;
        }

        public Builder post() {
            httpMethod = HttpMethod.POST;
            return this;
        }

        public Builder addHeader(String key, String value) {
            headers.put(key, value);
            return this;
        }

        public Builder map(Map<String, String> map) {
            headers.putAll(map);
            return this;
        }

        public Request build() {
            if (url == null) {
                throw new IllegalStateException("url不能为空");
            }
            if (body != null) {
                if (!TextUtils.isEmpty(body.contentType())) {
                    headers.put(Const.CONTENT_TYPE, body.contentType());
                }
            }
            headers.put(Const.CONNECTION, Const.KEEP_ALIVE);
            headers.put(Const.CHARSET, Const.UTF8);
            return new Request(this);
        }
    }
}
